package com.free;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.Base64;

/**
 * Hello world!
 *
 */
public class App 
{

    public static String getPublicKey(String filePath)
    {
        String key="";
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            FileInputStream in = new FileInputStream(filePath);

            //生成一个证书对象并使用从输入流 inStream 中读取的数据对它进行初始化。
            Certificate c = cf.generateCertificate(in);
            PublicKey publicKey = c.getPublicKey();
            key = Base64.getEncoder().encodeToString(publicKey.getEncoded());


        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return key;
    }

    public static void main( String[] args )
    {

        System.out.println(getPublicKey("C:\\Users\\Administrator\\Desktop\\ssl\\server.cer"));
    }
}
